import axios from 'axios'

function delay (duration) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, duration)
  })
}

export async function login (loginInfo) {
  // 模拟弱网络环境
  await delay(2000)
  // post http://study.yuanjin.tech/api/user/login
  var res = await axios.post('/api/user/login', loginInfo)
  var token = res.headers.authorization // 拿到服务器的令牌
  // console.log(token)
  if (token) {
    // 把令牌保存下来
    localStorage.setItem('token', token)
  }
  return res.data
}

// 使用保存的令牌从服务器换取登录信息
export async function whoAmI () {
  // 模拟弱网络环境
  await delay(2000)
  // get http://study.yuanjin.tech/api/user/whoami
  // authorization: bearer tokenxxxxx
  var token = localStorage.getItem('token')
  if (!token) {
    return null
  }
  var res = await axios.get('/api/user/whoami', {
    headers: {
      authorization: `bearer ${token}`
    }
  })
  return res.data.data
}

// 注销
export function logout () {
  localStorage.removeItem('token')
}

// 注册
export async function register (userInfo) {
  // post http://study.yuanjin.tech/api/user/reg
  var res = await axios.post('/api/user/reg', userInfo)
  return res.data
}
